class Ke {
  getTimestamp(milli?: boolean): number {
    const t: number = new Date().valueOf();
    return milli ? t : Math.ceil(t / 1000);
  }

  getRandom(min: number, max: number): number {
    return Math.floor(Math.random() * max + min);
  }

  randomString(len: number) {
    len = len || 32;
    let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let maxPos = $chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  array() {
    return {
      update(list: any[], key: any, data: any, pk: string = 'id') {
        const index = list.findIndex(_ => _[pk] == key);
        if (index >= -1) {
          list.splice(index, 1, { ...list[index], ...data });
        }
      },
      delete(list: any[], key: any, pk: string = 'id') {
        const index = list.findIndex(_ => _[pk] == key);
        if (index >= -1) {
          list.splice(index, 1);
        }
      },
      tree(
        list: any[],
        id: string = 'id',
        pid: string = 'pid',
        children: string = 'children',
      ) {
        if (!list) {
          return [];
        }
        let arr: any = JSON.parse(JSON.stringify(list));
        let map: any = {};
        for (let i = 0; i < arr.length; i++) {
          (map[arr[i][id]] as any) = arr[i];
        }
        let newArray: any = [];
        const f = () => {
          for (let i = 0; i < arr.length; i++) {
            let parent = map[arr[i][pid]];
            if (parent) {
              (parent[children] || (parent[children] = [])).push(arr[i]);
            } else {
              newArray.push(arr[i]);
            }
          }
        };
        f();
        return newArray;
      },
    };
  }

  /**
   * 将字符串转为头像
   * @param name
   */
  textToAvatar(name: string): string {
    // 设置初始值,防止name为空时程序无法执行
    let nick = '未知';
    // 判断name是否为空
    if (name) {
      nick = name.charAt(0);
    }
    const fontSize = 16;
    const fontWeight = 'normal';

    const canvas = document.createElement('canvas');
    canvas.width = 28;
    canvas.height = 28;
    const context = canvas.getContext('2d');
    if (!context) {
      return '';
    }
    // 头像背景颜色设置
    context.fillStyle = '#2D89EF';
    context.fillRect(0, 0, canvas.width, canvas.height);
    // 头像字体颜色设置
    context.fillStyle = '#FFFFFF';
    context.font = fontWeight + ' ' + fontSize + 'px sans-serif';
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillText(nick, canvas.width / 2, fontSize);
    return canvas.toDataURL('image/png');
  }
}

export const ke = new Ke();
